import java.util.LinkedList;
import java.util.Queue;

class MyStack {
    private final Queue<Integer> queue1;
    private final Queue<Integer> queue2;

    public MyStack() {
        queue1 = new LinkedList<>();
        queue2 = new LinkedList<>();
    }

    public void push(int x) {
        //只向有数的队列加数，或加到2
        if (!queue1.isEmpty()) {
            queue1.offer(x);
        } else {
            queue2.offer(x);
        }
    }

    public int pop() {
        //dest为空，src为存储地
        Queue<Integer> src = queue1.isEmpty() ? queue2 : queue1;
        Queue<Integer> dest = queue1.isEmpty() ? queue1 : queue2;

        //转移n-1，剩一个
        while (src.size() > 1) {
            dest.offer(src.poll());
        }

        return src.poll();
    }

    public int top() {
        int val = pop();
        //把它再放回
        push(val);
        return val;
    }

    public boolean empty() {
        return queue1.isEmpty() && queue2.isEmpty();
    }
}

// 测试代码示例
public class ImplementStackUsingQueues {
    public static void main(String[] args) {
        MyStack stack = new MyStack();
        stack.push(1);
        stack.push(2);
        System.out.println(stack.top());   // 输出 2
        System.out.println(stack.pop());   // 输出 2
        System.out.println(stack.empty()); // 输出 false
    }
}